package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 统一下单服务
     * @param orderId
     * @param money
     * @return
     */
    @RequestMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId") String orderId,@RequestParam("money") Integer money){

        Map map = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK,"统一下单成功",map);
    }

    @RequestMapping("/notify")
    public void nptifyLogic(HttpServletRequest request, HttpServletResponse response){
        System.out.println("支付回调成功");

        try{
            //将流转换成字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);

            //基于微信查询的订单信息来完成后续的业务逻辑
            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            if ("SUCCESS".equals(map.get("result_code"))){

                //查询订单
                Map result = wxPayService.queryOrder(map.get("out_trade_no"));

                //如果查询成功发送到mq
                if ("SUCCESS".equals(result.get("result_code"))){
                    Map message = new HashMap();
                    message.put("orderId",result.get("out_trade_no"));
                    message.put("transactionId",result.get( "transaction_id" ));

                    //发动信息到mq
                    rabbitTemplate.convertAndSend("","order_pay", JSON.toJSONString(message));


                    //通知跳转支付成功页面
                    rabbitTemplate.convertAndSend("paynotify","",result.get("out_trade_no"));


                }else {
                    //错误信息
                    System.out.println(result.get("err_code_des"));
                }
            }else {
                //错误信息
                System.out.println(map.get("err_code_des"));
            }

            //给微信平台一个响应
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭微信订单
     * @param orderId
     * @return
     */
    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable String orderId){
        Map map = wxPayService.closeOrder( orderId );
        return new Result( true,StatusCode.OK,"",map );
    }

    /**
     * 查询微信订单
     * @param orderId
     * @return
     */
    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable String orderId){
        Map map = wxPayService.queryOrder( orderId );
        return new Result( true,StatusCode.OK,"",map );
    }
}
